﻿using CommandProcessor.Command;
using Data.Infrastructure;
using Data.Models;
using Data.Repositories;
using Domain.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Domain.Handlers
{
    public class CreateOrUpdateBOMMachine_DetailsHandler : ICommandHandler<CreateOrUpdateBOMMachine_DetailsCommand>
    {
        private readonly IBOMMachine_DetailsRepository companyRepository;
        private readonly IUnitOfWork unitOfWork;
        public CreateOrUpdateBOMMachine_DetailsHandler(IBOMMachine_DetailsRepository companyRepository, IUnitOfWork unitOfWork)
        {
            this.companyRepository = companyRepository;
            this.unitOfWork = unitOfWork;
        }
        public ICommandResult Execute(CreateOrUpdateBOMMachine_DetailsCommand command)
        {
            var company = new BOMMachine_Details
            {
                ID = command.ID,
                Description = command.Description,
                BOMID = command.BOMID,
                Quantity = command.Quantity,
                UnitID = command.UnitID,
                MachineID = command.MachineID,
                Price=command.Price,
                Amount=command.Amount,
                
            };
            if (company.ID == 0)
                companyRepository.Add(company);
            else
                companyRepository.Update(company);

            unitOfWork.Commit();
            return new CommandResult(true);
        }
        public ICommandResult ExecuteRange(IEnumerable<CreateOrUpdateBOMMachine_DetailsCommand> commands)
        {
            List<BOMMachine_Details> list = new List<BOMMachine_Details>();
            foreach (var item in commands)
            {
                var company = new BOMMachine_Details
                {
                    ID = item.ID,
                    Description = item.Description,
                    BOMID = item.BOMID,
                    MachineID = item.MachineID,
                    Quantity = item.Quantity,
                    UnitID = item.UnitID,
                    Price=item.Price,
                    Amount=item.Amount
                };
                list.Add(company);
            }
            if (list.Any(x => x.ID == 0))
                companyRepository.AddRange(list.Where(x => x.ID == 0));
            else
                companyRepository.UpdateRange(list.Where(x => x.ID != 0));
            unitOfWork.Commit();
            return new CommandResult(true);
        }
        public ICommandResult DeleteRange(IEnumerable<CreateOrUpdateBOMMachine_DetailsCommand> commands)
        {
            var ids = commands.Select(y => y.ID);
            companyRepository.Delete(x => ids.Contains(x.ID));
            unitOfWork.Commit();
            return new CommandResult(true);
        }
    }
}
